import React, { useEffect, useState } from 'react'

import { NavBar } from 'antd-mobile'

import HouseItem from '../../components/HouseItem'
import NoHouse from '../../components/NoHouse'

import { API, BASE_URL } from '../../utils'

import styles from './index.module.css'
import { Link } from 'react-router-dom'

export default function Rent({ history }) {
  const [houseList, setHouseList] = useState([])
  const [isLoading, setIsLoading] = useState(false)

  useEffect(() => {
    const getHouseList = async () => {
      setIsLoading(true)
      const { data: res } = await API.get('/user/houses')
      setIsLoading(false)
      setHouseList(res.body)
    }

    getHouseList()
  }, [])

  const renderHouseItem = () => {
    return houseList.map(item => (
      <HouseItem
        key={item.houseCode}
        onClick={() => history.push(`/detail/${item.houseCode}`)}
        src={BASE_URL + item.houseImg}
        title={item.title}
        desc={item.desc}
        tags={item.tags}
        price={item.price}
      />
    ))
  }

  const renderRentList = () => {
    if (!houseList.length && !isLoading) {
      return (
        <NoHouse>
          您还没有房源，
          <Link to="/rent/add" className={styles.link}>
            去发布房源
          </Link>
          吧~
        </NoHouse>
      )
    }

    return renderHouseItem()
  }

  return (
    <div className={styles.root}>
      <NavBar onBack={() => history.go(-1)}>房屋管理</NavBar>

      <div className={styles.houseList}>{renderRentList()}</div>
    </div>
  )
}
